﻿using CnControls;
using Models;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public enum PlayerFaceDir
{
    Left,
    Right,
    Up,
    Down
}

public class BaseControlMove : MonoBehaviour {

    // Use this for initialization

    //private Vector3[] directionalVectors = { Vector3.down, Vector3.up, Vector3.left, Vector3.right };

    public PlayerFaceDir facedir;

    private Vector2 currentDir ;
    public bool playerCanMove = true;

    public float speed;

    public Vector3 Now_transformedDirection;

    Vector2 CheckPosIsInWSAD(Vector2 _pos)
    {
        //如果 x,y点 在 某区域内   那么返回，，，
        //如果 y > - x  并且 y > x 返回  0，1       上面扇形区域

        if (_pos.y > -_pos.x && _pos.y > _pos.x)
        {
            return new Vector2(0, 1);
        }

        //如果 y < x 并且 y < - x  返回  0, -1      下面扇形区域
        else if (_pos.y < _pos.x && _pos.y < -_pos.x)
        {
            return new Vector2(0, -1);
        }
        //如果  y > x 并且  y < -x 返回  -1, 0      左边扇形区域
        else if (_pos.y > _pos.x && _pos.y < -_pos.x)
        {
            return new Vector2(-1, 0);
        }
        //如果  y < x 并且  y > -x  返回  1，0      右边扇形区域
        else if (_pos.y < _pos.x && _pos.y > -_pos.x)
        {
            return new Vector2(1, 0);
        }
        else
        {
            return Vector2.zero;
        }
    }


    enum PlayerState
    {
        standing = 0,
        running = 1
    };

    // public Texture2D _spriteTexture;
    // public int rows;
    public int cols;
    public int targetFrameRate = 45;

    private SpriteRenderer _spriteRender;
    // private ArrayList _sprites;

    [Header("角色人物的上下左右各4张行走图")]
    public Sprite[] _spritesLeft;
    public Sprite[] _spritesRight;
    public Sprite[] _spritesUp;
    public Sprite[] _spritesDown;
    [Header("坦克的上下左右各4张行走图")]
    public Sprite[] tank_spritesLeft;
    public Sprite[] tank_spritesRight;
    public Sprite[] tank_spritesUp;
    public Sprite[] tank_spritesDown;




    private PlayerState _state;

    private int index;
    private int currentIndex;
    private int newIndex;

    public float intervalTime;/*delay time 图片切换速度*/
    private float interval;

    void Start()
    {
        facedir = PlayerFaceDir.Down;
        _spriteRender = this.GetComponent(typeof(SpriteRenderer)) as SpriteRenderer;
        _state = PlayerState.standing;

        index = 0;
        currentIndex = 0;
        newIndex = 0;

        currentDir = new Vector2(0, 0);

        interval = intervalTime;

        Application.targetFrameRate = targetFrameRate;
        //这里要根据数据库判断到底是显示战车 还是 人物
        CheckPersonIsDriveTankToShow();


    }

    void CheckPersonIsDriveTankToShow()
    {
        bool p1_IsDriveTank;
        try
        {
             p1_IsDriveTank = GameDataManager.Instance.CheckPersonIsDriveTank();
        }

        catch
        {
            p1_IsDriveTank = false;
            Debug.LogError("CheckPersonIsDriveTankToShow 没有找到数据，初始化还没有完成哦");
        }
        if (p1_IsDriveTank)
        {
            SetPlayerDriveTank();
            _spriteRender.sprite = tank_spritesDown[0] as Sprite;

        }
        else
        {
            _spriteRender.sprite = _spritesDown[0] as Sprite;
        }
    }


    void PlayerMoveFunc()
    {

        if (playerCanMove)
        {

            /*move player*/
             this.transform.Translate( currentDir * Time.deltaTime * speed);
            //this.transform.Translate(Now_transformedDirection * Time.deltaTime * speed);

            
            //this.transform.Translate(new Vector2(1, 0) * Time.deltaTime);
            /*锁定旋转，防治碰撞产生倾斜角度感觉*/
            this.gameObject.transform.rotation = new Quaternion(0f, 0f, 0f, 0f);


        }
    }

    bool GetInputKeyDownHold(KeyCode k)
    {

        return Input.GetKey(k);
    }

    bool CheckInputKeyNotDown(KeyCode k)
    {
        return !(Input.GetKey(k));
    }

    void CheckInput_To_SetCurrentDir()
    {

        if (GetInputKeyDownHold(KeyCode.W) && CheckInputKeyNotDown(KeyCode.S) && CheckInputKeyNotDown(KeyCode.A) && CheckInputKeyNotDown(KeyCode.D) || Now_transformedDirection == new Vector3(0,1,0))
        {
            //只按了W键
            Debug.Log("Just W");
            currentDir = new Vector2(0, 1);
            facedir = PlayerFaceDir.Up;
            if (_state == PlayerState.standing)
                _state = PlayerState.running;

            newIndex = 1;
            if (newIndex != currentIndex)
                currentIndex = newIndex;

        }

        else if (GetInputKeyDownHold(KeyCode.S) && CheckInputKeyNotDown(KeyCode.W) && CheckInputKeyNotDown(KeyCode.A) && CheckInputKeyNotDown(KeyCode.D) || Now_transformedDirection == new Vector3(0, -1, 0))
        {
            //只按了S键
            currentDir = new Vector2(0, -1);
            facedir = PlayerFaceDir.Down;
            if (_state == PlayerState.standing)
                _state = PlayerState.running;

            newIndex = 3;
            if (newIndex != currentIndex)
                currentIndex = newIndex;

        }

        else if (GetInputKeyDownHold(KeyCode.A) && CheckInputKeyNotDown(KeyCode.D) && CheckInputKeyNotDown(KeyCode.W) && CheckInputKeyNotDown(KeyCode.S) || Now_transformedDirection == new Vector3(-1,0, 0))
        {
            //只按了A键
            currentDir = new Vector2(-1, 0);
            facedir = PlayerFaceDir.Left;
            if (_state == PlayerState.standing)
                _state = PlayerState.running;

            newIndex = 2;
            if (newIndex != currentIndex)
                currentIndex = newIndex;

        }
        else if (GetInputKeyDownHold(KeyCode.D) && CheckInputKeyNotDown(KeyCode.A) && CheckInputKeyNotDown(KeyCode.W) && CheckInputKeyNotDown(KeyCode.S) || Now_transformedDirection == new Vector3( 1, 0, 0))
        {
            //只按了D键
            currentDir = new Vector2(1, 0);
            facedir = PlayerFaceDir.Right;
            if (_state == PlayerState.standing)
                _state = PlayerState.running;

            newIndex = 0;
            if (newIndex != currentIndex)
                currentIndex = newIndex;
        }


        else if (CheckInputKeyNotDown(KeyCode.A) && CheckInputKeyNotDown(KeyCode.D) && CheckInputKeyNotDown(KeyCode.W) && CheckInputKeyNotDown(KeyCode.S) || Now_transformedDirection == new Vector3(0, 0, 0))
        {
            //ADWS都没有被按下
            currentDir = new Vector2(0, 0);

        }


    }

    void SpriteAnimation()
    {
        if (_state == PlayerState.running)
        {
            interval -= Time.deltaTime;
            if (interval <= 0)
            {
                index++;


                // % 取模运算符，整除后的余数 1,2,3,4 除以4，，
                // Debug.Log("NowIndex:" + index + "  取模值为：" + index % cols);
                _spriteRender.sprite = GetSpriteByIndex(currentIndex) as Sprite;

                /*init interval Time*/
                interval = intervalTime;
            }

          
        }

        if (CheckInputKeyNotDown(KeyCode.A) && CheckInputKeyNotDown(KeyCode.D) && CheckInputKeyNotDown(KeyCode.W) && CheckInputKeyNotDown(KeyCode.S) || Now_transformedDirection == new Vector3(0, 0, 0))
        {
            //ADWS都没有被按下
            if (_state == PlayerState.running)
                _state = PlayerState.standing;

        }

    }

    bool isDriveTank = false;

    public void SetPlayerDriveTank()
    {

        isDriveTank = true;
        _spriteRender.sprite = tank_spritesDown[0] as Sprite;
        SetNow_transformedDirectionNull();
    }

    Sprite GetSpriteByIndex(int _index)
    {
        if (isDriveTank)
        {
            if (_index == 1)
            {
                return tank_spritesUp[index % cols];
            }
            if (_index == 3)
            {
                return tank_spritesDown[index % cols];
            }
            if (_index == 2)
            {
                return tank_spritesLeft[index % cols];
            }
            else
            {
                return tank_spritesRight[index % cols];
            }
        }
        else
        {
            if (_index == 1)
            {
                return _spritesUp[index % cols];
            }
            if (_index == 3)
            {
                return _spritesDown[index % cols];
            }
            if (_index == 2)
            {
                return _spritesLeft[index % cols];
            }
            else
            {
                return _spritesRight[index % cols];
            }
        }
    }

    public void OpenPlayerMove()
    {
        playerCanMove = true;
    }

    public void ClosePlayerMove()
    {
        playerCanMove = false;
    }


    public void SetNow_transformedDirectionNull()
    {
        Now_transformedDirection = Vector3.zero;
        StartCoroutine(Set_Now_transformedDirection_Zero());
        
    }

    IEnumerator Set_Now_transformedDirection_Zero()
    {
        playerCanMove = false;
        Now_transformedDirection = Vector3.zero;
        yield return new WaitForSeconds(2f);
        Now_transformedDirection = Vector3.zero;

       
        playerCanMove = true;
        
    }

    Vector2 tempPos;
    Vector2 endPos;
    void Update()
    {
        if (playerCanMove)
        {

            //if (CnInputManager.TouchCount > 0)
            //{
                 tempPos = new Vector2(CnInputManager.GetAxis("Horizontal"), CnInputManager.GetAxis("Vertical"));
            //}
             endPos = CheckPosIsInWSAD(tempPos);
            Now_transformedDirection = new Vector3(endPos.x, endPos.y, 0);

            // Debug.Log(currentDir);
            // Debug.Log("W is key down:" + Input.GetKeyDown(KeyCode.W) + "  "+ Input.GetKey(keycow));
            PlayerMoveFunc();
            CheckInput_To_SetCurrentDir();

            SpriteAnimation();

           // Debug.Log(Now_transformedDirection);
        }
    }
}
